package at.irian.jsfatwork.jsf;

import org.apache.myfaces.shared_impl.renderkit.html.HTML;

import javax.faces.application.StateManager;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;

/**
 * @author Thomas Spiegl, IRIAN Solutions GmbH
 */
public class JsfStateManager extends StateManager {

    public UIViewRoot restoreView(FacesContext context, String viewId, String renderKitId) {
        return context.getApplication().getViewHandler().createView(context, viewId);
    }

    public Object saveView(FacesContext context) {
        return new Object();
    }

    public boolean isSavingStateInClient(FacesContext context) {
        return true;
    }

    public void writeState(FacesContext context, Object state) throws IOException {
        internalWriteState(context);
    }

    private void internalWriteState(FacesContext context) throws IOException {
        ResponseWriter responseWriter = context.getResponseWriter();
        responseWriter.startElement(HTML.INPUT_ELEM, null);
        responseWriter.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN, null);
        responseWriter.writeAttribute(HTML.NAME_ATTR, "javax.faces.ViewState", null);
        responseWriter.writeAttribute(HTML.VALUE_ATTR, "0", null);
        responseWriter.endElement(HTML.INPUT_ELEM);
    }

    protected Object getTreeStructureToSave(FacesContext context) {
        return new Object();
    }

    protected Object getComponentStateToSave(FacesContext context) {
        return new Object();
    }

    protected UIViewRoot restoreTreeStructure(FacesContext context, String viewId, String renderKitId) {
        throw new NullPointerException("JsfStateManager not supported");
    }

    protected void restoreComponentState(FacesContext context, UIViewRoot viewRoot, String renderKitId) {
    }

    public void writeState(FacesContext context, SerializedView state) throws IOException {
        internalWriteState(context);
    }

    public SerializedView saveSerializedView(FacesContext context) {
        return new SerializedView(new Object(), new Object());
    }
}
